// base
import Taro, { Component } from '@tarojs/taro'
import { View, Image, Form, Button, ScrollView } from '@tarojs/components'
import { connect } from '@tarojs/redux'
import { AtActivityIndicator, AtSwipeAction, AtList } from 'taro-ui'
// redux
import { DOREQUESTMESSAGELIST } from './store/actions/pagemessagelist'
import { UPDATEPAGEMESSAGELIST } from './store/types/pagemessagelist'
import { UPDATEIM } from '../../store/types/im'
import { UPDATEUSERINFO } from '../../store/types/userinfo'
import {
  getZhichuBUserInfo,
  getZhichuUserInfo,
  updateCompanyId
} from '../../store/actions/userinfo'
import { DOREQUESTCHANGECP } from '../self-center/store/actions/pageselfcenter'
// less
import './index.less'

// componnet
import scaleImageSrc from '../../util/pagemethods/scaleImageSrc'
import If from '../../components/page-components/if'
import { navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import messagePush from '../../util/messagePush'
import ShowNull from '../../components/page-components/show-null'
import wxLogin from '../../util/wxLogin'
import IMController from '../../util/wy_im'
import { avater, avaterB, dealImgUrl } from '../../configuration/staticimg'
import { showToast } from '../../crossplatform/apiservice/toast'
import { getStorageSync } from '../../crossplatform/apiservice/storage'
import tool from '../../util/tool'

const mapActiontoProps = dispatch => ({
  updateState (payload) {
    dispatch({
      type: UPDATEPAGEMESSAGELIST,
      payload: {
        ...payload
      }
    })
  },
  updateImState (payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  updateUserState (payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  getZhichuUserInfo (payload) {
    return new Promise(resolve => {
      let promise = getZhichuUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  getZhichuBUserInfo (payload) {
    return new Promise(resolve => {
      let promise = getZhichuBUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  updateCompany () {
    dispatch(updateCompanyId())
  },
  queryCompanyInfo (payload) {
    return dispatch(DOREQUESTCHANGECP(payload))
  },
  dorequest () {
    return new Promise(resolve => {
      let promise = DOREQUESTMESSAGELIST()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagemessagelist, userinfo, im }) => ({
    ...pagemessagelist,
    ...userinfo,
    ...im
  }),
  mapActiontoProps
)
class MessageList extends Component {
  config = {
    navigationBarTitleText: '',
    disableScroll: true
  }
  constructor (props) {
    super(props)
    this.state = {
      dataLoading: true,
      isInLoad: false,
      swipeActionOptions: [
        {
          text: '删除',
          style: {
            display: 'inline-flex',
            backgroundColor: '#FF4949',
            width: '60px',
            justifyContent: 'center',
            marginLeft: '10px'
          }
        }
      ],
      isOpened: [],
      isiPhone: false
    }
  }

  componentWillMount () {
    // onLoad
    this.wxLogin()
    // 判断是否是iphone
    this.setState({
      isiPhone: getStorageSync('iPhone')
    })
  }

  componentDidMount () {
    // onready
  }

  componentDidShow () {
    // onshow
    if (!this.state.isInLoad) {
      this.queryWrap()
    }
    const { sessions = [] } = IMController.props || this.props
    IMController.checkRedDot(sessions)
  }

  componentDidHide () {
    // onhide
    this.setState({
      isInLoad: false,
      isOpened: []
    })
  }

  componentWillUnmount () {
    // onUnload
  }

  queryWrap = () => {
    this.setState({
      dataLoading: true
    })

    // 设置右滑状态
    const { contactList } = this.props
    let isOpened = []
    contactList.map(item => {
      isOpened.push(false)
      return item
    })

    this.setState({
      dataLoading: false,
      isOpened
    })
  }

  wxLogin = () => {
    const { message = '', role = '' } = this.$router && this.$router.params
    if (message) {
      this.setState({
        isInLoad: true
      })
      this.noticeIn(role)
      wxLogin.props = this.props
      wxLogin.doLogin().then(() => {
        const { companyId } = this.props
        IMController.queryWrap().then(() => {
          this.queryWrap()
        })

        companyId && this.getVipStatus({ companyId })

        wxLogin.getArchiveInfo()
      })
    }
  }

  goChat = tool.throttle(e => {
    const { account } = e.currentTarget.dataset
    this.props.updateImState({
      selToID: account,
      msgArray: [],
      currentSessionId: `p2p-${account}`
    })
    // IMController.updateUnreadInfo(`p2p-${account}`)
    navigateTo({
      url: `${pagejumplist['chat-page'].path}`
    })
  })

  formSubmit = e => {
    let { formId } = e.detail
    const { openId, userId } = this.props
    messagePush.insertFormId({ userId, formId, openId })
  }

  noticeIn = role => {
    // 通过推送消息进入该页面 (公司审核通过)
    if (role == 'company') {
      this.props.updateUserState({
        role: 'company'
      })
    }
  }

  swiperClick = (account, key) => {
    if (key.text == '删除') {
      IMController.delChat({ toId: account }).then(() => {
        // 设置右滑状态
        const { contactList } = this.props
        let contactListNew = [...contactList]
        let isOpened = []
        contactListNew.map((item, index) => {
          isOpened.push(false)
          if (item.account == account) {
            contactListNew.splice(index, 1)
          }
          return item
        })
        this.props.updateImState({
          contactList: contactListNew
        })
        this.setState({
          isOpened
        })
      })
    }
  }

  getVipStatus = ({ companyId }) => {
    const { role } = this.props
    role == 'company' && this.props.queryCompanyInfo({ companyId }).then(({ payload: { status, entry, message } }) => {
      if (status) {
        this.props.updateUserState({
          isVip: !!entry
        })
      } else {
        showToast({
          title: message || 'queryCompanyInfo失败'
        })
      }
    })
  }

  handleSingle = index => {
    // 控制只能滑动一个
    const { contactList } = this.props
    let isOpened = []
    let contactListNew = [...contactList]
    contactListNew.map((item, key) => {
      isOpened.push(key === index)
      return item
    })

    this.setState({
      isOpened
    })
  }

  setDefaultHeadUrl = (role, gender, userId = 0) => {
    return role === 'personal'
      ? avaterB(gender)
      : avater(gender, userId)
  }

  render () {
    const { contactList, role } = this.props
    const { dataLoading, swipeActionOptions, isOpened, isiPhone } = this.state

    return (
      <View className="MessageList_id80290">
        <View className="title">
          <View className="content">
            <View className="name">消息</View>
            <View className="number">{contactList.length || '0'}</View>
          </View>
        </View>
        <If
          visible={!dataLoading}
          renderElse={<AtActivityIndicator content="加载中..." mode="center" />}
        >
          <If
            visible={contactList && contactList.length}
            renderElse={
              <ShowNull
                imgUrl="https://imagesize.hrwork.com/sp/files/46b024dc-498b-4dff-a5fc-a6364b822863.png"
                text={role === 'personal' ? '快去和企业交流吧～' : '快去和人才交流吧～'}
              />
            }
          >
            <ScrollView className="list-content" scrollY>
              <AtList className={`message-list  ${isiPhone ? 'message-list-padding' : ''}`}>
                {contactList.map((item, index) => {
                  let avatarUrl =
                    item.avatarUrl && item.avatarUrl != 'null'
                      ? item.avatarUrl
                      : this.setDefaultHeadUrl(role, item.gender, item.account ? parseInt(item.account) : 0)
                  return (
                    <AtSwipeAction
                      autoClose
                      key={index}
                      data-e-onclick-a-a={item.account}
                      options={swipeActionOptions}
                      onClick={this.swiperClick.bind(this, item.account)}
                      onOpened={this.handleSingle.bind(this, index)}
                      isOpened={isOpened[index]}
                      className="list-item"
                    >
                      <Form onSubmit={this.formSubmit} reportSubmit>
                        <Button
                          formType="submit"
                          className="form-btn"
                          data-account={item.account}
                          onClick={this.goChat}
                        >
                          <Image
                            className="header-img"
                            src={scaleImageSrc(dealImgUrl(avatarUrl), 104)}
                            mode="aspectFill"
                          />
                          <View className="item-middle">
                            <View className="item-top">
                              <View className="item-name">{item.nick}</View>
                              <View className="item-company">{item.sign}</View>
                            </View>
                            <View className="item-msg">{item.lastMsg}</View>
                          </View>
                          <View className="item-msgTime">{item.msgTime}</View>
                          <If visible={item.unread > 0}>
                            <View className="unread-count">{item.unread > 99 ? '99+' : item.unread}</View>
                          </If>
                        </Button>
                      </Form>
                    </AtSwipeAction>
                  )
                })}
              </AtList>
            </ScrollView>
          </If>
        </If>
      </View>
    )
  }
}

export default MessageList
